
//
// 130424 - AH - Created.
//

package org.japril.swing.jutil.xmloperations;

import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;

import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JTable;

import org.japril.jutil.xmloperations.XmlOperation;
import org.japril.swing.ExceptionDialog;
import org.japril.swing.PopupListener;

/**
 * <p>
 * </p>
 * @author Arne Halvorsen (AH)
 */
@SuppressWarnings("serial")
public final class XmlOperationPathsPanel extends JPanel
{
  private XmlOperationPathTableModel m_model=new XmlOperationPathTableModel();
  
  private final JTable m_table=new JTable(m_model);
  
  /**
   * <p>
   *   Constructor.
   * </p>
   */
  public XmlOperationPathsPanel()
  {
    setLayout(new BorderLayout());
    
    JPanel north=new JPanel(new FlowLayout(FlowLayout.CENTER));
    north.add(new JLabel("Paths"));
    add(north, BorderLayout.NORTH);
    
    JScrollPane sp=new JScrollPane(m_table);
    add(sp, BorderLayout.CENTER);
    
    JPopupMenu pm=new JPopupMenu();
    pm.add(m_create);
    pm.add(m_remove);
    new PopupListener(pm, sp);
  }
  
  public final Action m_create=new AbstractAction("Create XPath")
  {
    public void actionPerformed(ActionEvent e)
    {
      String path=JOptionPane.showInputDialog("XPath");
      path=(path==null) ? "" : path.trim();
      if (path.length()>0)
      {
        try
        {
          m_model.addPath(path);
        }
        catch (Exception x)
        {
          ExceptionDialog.showErrorDialog(x);
        }
      }
    }
  };
  
  public final Action m_remove=new AbstractAction("Remove XPath")
  {
    public void actionPerformed(ActionEvent e)
    {
      int idx=m_table.getSelectedRow();
      if (idx!=-1)
      {
        try
        {
          m_model.removePath(idx);
        }
        catch (Exception x)
        {
          ExceptionDialog.showErrorDialog(x);
        }
      }
    }
  };
  
  /**
   * <p>
   *   Sets
   *   {@link XmlOperation} to view paths for.
   * </p>
   * @param o {@link XmlOperation} or {@code null} if to clear.
   */
  public void setOperation(XmlOperation o)
  {
    m_model=new XmlOperationPathTableModel(o);
    m_table.setModel(m_model);
  }
  
}
